package edu.sctu.wangfuxin.day20150623.test_Json;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by user06 on 2015/6/23.
 */
public class JsonUtil {

    /**
     * 获取Json数据
     *
     * @param path URL
     * @return Json数据
     */
    public String getJson(String path) {
        int count;
        String string = "";
        byte[] buffer = new byte[1024];
        try {
            URL url = new URL(path);
            try {
                URLConnection urlConnection = url.openConnection();
                urlConnection.connect();
                InputStream inputStream = urlConnection.getInputStream();
                while ((count = inputStream.read(buffer)) != -1) {
                    string = string + new String(buffer, 0, count, "utf-8");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return string;
    }


    /**
     * 解析Json
     */
    public Data jiexiJson(String json) {

        JSONObject jsonObject = JSON.parseObject(json);

        Data data = new Data();
        data.error = jsonObject.getInteger("error");
        data.count = jsonObject.getString("count");
        data.message = jsonObject.getString("message");
        data.page = jsonObject.getInteger("page");
        data.size = jsonObject.getInteger("size");

//        JSONArray list = jsonObject.getJSONArray("list");
        String list1 = jsonObject.getString("list");
        JSONArray jsonArray = JSON.parseArray(list1);

        for (int i = 0; i < jsonArray.size(); i++) {
            ListData data1 = new ListData();
//            String x = list.getString(i);
//            JSONObject jsonObject1 = JSONObject.parseObject(x);
            data1.goods_id = jsonArray.getJSONObject(i).getString("goods_id");
            data1.goods_name =jsonArray.getJSONObject(i).getString("goods_name");
            data1.goods_price = jsonArray.getJSONObject(i).getString("goods_price");
            data.list.add(data1);
        }

        return data;
    }

    /**
     * 快速解析Json
      * @return
     */

    public Data jiexiJson1(String json){
       Data jsonData = JSON.parseObject(json,Data.class);

        return jsonData;
    }

}
